<template>
  <div class="forgot-password-container">
    <div class="forgot-password-card">
      <div class="forgot-password-header">
        <h1>找回密码</h1>
        <p>请输入注册时使用的手机号</p>
      </div>

      <el-form
        ref="resetFormRef"
        :model="resetForm"
        :rules="resetRules"
        class="reset-form"
        size="large"
      >
        <!-- 手机号 -->
        <el-form-item prop="phone">
          <el-input
            v-model="resetForm.phone"
            placeholder="请输入手机号"
            prefix-icon="Phone"
          />
        </el-form-item>

        <!-- 验证码功能已关闭，暂不需要验证码 -->

        <!-- 新密码 -->
        <el-form-item prop="newPassword">
          <el-input
            v-model="resetForm.newPassword"
            type="password"
            placeholder="请输入新密码（至少6位）"
            prefix-icon="Lock"
            show-password
          />
        </el-form-item>

        <!-- 确认密码 -->
        <el-form-item prop="confirmPassword">
          <el-input
            v-model="resetForm.confirmPassword"
            type="password"
            placeholder="请再次输入新密码"
            prefix-icon="Lock"
            show-password
            @keyup.enter="handleResetPassword"
          />
        </el-form-item>

        <!-- 提交按钮 -->
        <el-form-item>
          <el-button
            type="primary"
            class="reset-button"
            :loading="loading"
            @click="handleResetPassword"
          >
            重置密码
          </el-button>
        </el-form-item>

        <!-- 底部链接 -->
        <div class="reset-footer">
          <el-link type="primary" @click="goToLogin">返回登录</el-link>
          <span style="margin: 0 10px">|</span>
          <el-link type="primary" @click="goToRegister">立即注册</el-link>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { sendVerifyCode, resetPassword } from '@/api/user'

const router = useRouter()

const resetFormRef = ref()
const loading = ref(false)
const sendingCode = ref(false)
const countdown = ref(0)
let countdownTimer = null

const resetForm = reactive({
  phone: '',
  verifyCode: '',
  newPassword: '',
  confirmPassword: ''
})

// 自定义验证规则：确认密码
const validateConfirmPassword = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== resetForm.newPassword) {
    callback(new Error('两次输入的密码不一致'))
  } else {
    callback()
  }
}

const resetRules = {
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  // 验证码验证已关闭
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, message: '密码长度至少6位', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    { validator: validateConfirmPassword, trigger: 'blur' }
  ]
}

// 发送验证码
const handleSendCode = async () => {
  // 先验证手机号
  try {
    await resetFormRef.value.validateField('phone')
  } catch (error) {
    return
  }

  sendingCode.value = true
  try {
    await sendVerifyCode({
      phone: resetForm.phone,
      type: 'reset_password'
    })
    
    ElMessage.success('验证码已发送（模拟）')
    
    // 开始倒计时
    countdown.value = 60
    countdownTimer = setInterval(() => {
      countdown.value--
      if (countdown.value <= 0) {
        clearInterval(countdownTimer)
      }
    }, 1000)
  } catch (error) {
    ElMessage.error(error.message || '发送验证码失败')
  } finally {
    sendingCode.value = false
  }
}

// 重置密码（暂不验证验证码）
const handleResetPassword = async () => {
  await resetFormRef.value.validate(async (valid) => {
    if (valid) {
      loading.value = true
      try {
        const response = await resetPassword({
          phone: resetForm.phone,
          verifyCode: '', // 暂不验证验证码，传空字符串
          newPassword: resetForm.newPassword
        })
        
        if (response.success) {
          ElMessage.success('密码重置成功，请使用新密码登录')
          setTimeout(() => {
            router.push('/login')
          }, 1500)
        } else {
          ElMessage.error(response.message || '密码重置失败')
        }
      } catch (error) {
        ElMessage.error(error.message || '密码重置失败')
      } finally {
        loading.value = false
      }
    }
  })
}

// 返回登录
const goToLogin = () => {
  router.push('/login')
}

// 前往注册
const goToRegister = () => {
  router.push('/register')
}

// 组件卸载时清除定时器
import { onBeforeUnmount } from 'vue'
onBeforeUnmount(() => {
  if (countdownTimer) {
    clearInterval(countdownTimer)
  }
})
</script>

<style scoped>
.forgot-password-container {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding: 20px;
}

.forgot-password-card {
  background: white;
  border-radius: 16px;
  padding: 40px;
  width: 100%;
  max-width: 450px;
  box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
}

.forgot-password-header {
  text-align: center;
  margin-bottom: 30px;
}

.forgot-password-header h1 {
  color: #333;
  font-size: 28px;
  margin-bottom: 10px;
  font-weight: 600;
}

.forgot-password-header p {
  color: #666;
  font-size: 14px;
}

.reset-form {
  margin-top: 20px;
}

.verify-code-wrapper {
  display: flex;
  gap: 10px;
  width: 100%;
}

.reset-button {
  width: 100%;
  height: 45px;
  font-size: 16px;
  font-weight: 500;
  border-radius: 8px;
}

.reset-footer {
  text-align: center;
  padding-top: 20px;
  color: #666;
  font-size: 14px;
}

.reset-footer .el-link {
  font-size: 14px;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .forgot-password-card {
    padding: 30px 20px;
  }

  .forgot-password-header h1 {
    font-size: 24px;
  }
}
</style>
